package com.linb.pan.stream.core;

import com.google.common.collect.Maps;
import com.linb.pan.core.exception.BPanFrameworkException;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;

import java.util.Map;
import java.util.Objects;

/**
 * 消息发送者顶级抽象父类
 */
public abstract class AbstractStreamProducer implements IStreamProducer {

    @Autowired
    private Map<String, MessageChannel> channelMap;

    @Override
    public boolean sendMessage(String channelName, Object deploy) {
        return sendMessage(channelName, deploy, Maps.newHashMap());
    }

    @Override
    public boolean sendMessage(String channelName, Object deploy, Map<String, Object> headers) {
        //校验参数
        if (StringUtils.isBlank(channelName) || Objects.isNull(deploy)) {
            throw new BPanFrameworkException("channelName或deploy不能为空!");
        }
        if (MapUtils.isEmpty(channelMap)) {
            throw new BPanFrameworkException("channelMap不能为空!");
        }
        MessageChannel channel = channelMap.get(channelName);
        if (Objects.isNull(channel)) {
            throw new BPanFrameworkException("channelName为{}的channel不能为空!" + channelName);
        }
        Message message = MessageBuilder.createMessage(deploy, new MessageHeaders(headers));
        //执行发送消息前的钩子函数
        preSend(message);
        boolean result = channel.send(message);
        //执行发送消息后的钩子函数
        afterSend(message, result);
        return result;
    }

    /**
     * 发送消息前的钩子函数
     */
    protected abstract void preSend(Message message);

    /**
     * 发送消息后的钩子函数
     */
    protected abstract void afterSend(Message message, boolean result);

}
